package org.prj;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;

public class MyClassLoader extends URLClassLoader{

	@SuppressWarnings("rawtypes")
	Set<Class> classLoaded=new HashSet<>();
	
	private static String base="jar:file:///Applications/development/apache-tomcat-7.0.35/lib/dynamic/";
	private static String end="!/";
	//private static String end="";
	
	private static String[] urls={"test.jar"};
	
	private static URL[] urlArr=new URL[0];
	
	static{
		urlArr=new URL[urls.length];
		for(int i=0;i<urls.length;i++){
			try {
				urlArr[i]=new URL(base+urls[i]+end);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
    public MyClassLoader(ClassLoader parent) {
    	
    	super(new URL[0], parent);
        
    	reload();
    }
    
    public void reload(){
    	for(URL url: urlArr){
    		try {
				ClassLoaderUtil.addURL(url, this);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    }
    
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {    	
    	//if(name.startsWith("java."))
    		return super.loadClass(name);
    	
    }

//    @SuppressWarnings({ "rawtypes", "unchecked" })
//	public Class loadClass(String name) throws ClassNotFoundException {
//    	if(name.startsWith("java."))
//    		return super.loadClass(name);
//
//        try {
//        	
//            String url = "file:/Users/dmac/Documents/workspace/ee_4_3/TestClassReload/build/classes/org/prj/MyObject.class";
//            URL myUrl = new URL(url);
//            URLConnection connection = myUrl.openConnection();
//            InputStream input = connection.getInputStream();
//            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
//            int data = input.read();
//
//            while(data != -1){
//                buffer.write(data);
//                data = input.read();
//            }
//
//            input.close();
//
//            byte[] classData = buffer.toByteArray();
//
//            
//            
//            return defineClass(name,
//                    classData, 0, classData.length);
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace(); 
//        }
//
//        return null;
//    }

}